package cn.edu.seu.herald.informationplatform.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import cn.edu.seu.herald.informationplatform.bean.league.Activity;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.ActivityDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;

public class editActivityShowPic extends HttpServlet {

	public Activity addConvertedPic(Activity activity,File saveFile,String savePathMin,String relativeSavePathMin){
		try{    
			Image src = ImageIO.read(saveFile);             
			double old_w=src.getWidth(null);                                     
			double old_h=src.getHeight(null);   
			double new_w=0;
			double new_h=0;
			double w_standard=380;
			double h_standard=212;
			double w_h_rate = old_w/old_h;
			double w_h_rate_standard = w_standard/h_standard;
			
			double tempdouble; 
			if(w_h_rate>w_h_rate_standard){
			tempdouble=old_w/w_standard;
			}else{
			tempdouble=old_h/h_standard;
			}
			new_w=Math.round(old_w/tempdouble);
			new_h=Math.round(old_h/tempdouble);//计算新图长宽
			BufferedImage tag = new BufferedImage((int)new_w,(int)new_h,BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src,0,0,(int)new_w,(int)new_h,null); 
			
			FileOutputStream newimage=new FileOutputStream(savePathMin);          //输出到文件流
			activity.setPostAddress(relativeSavePathMin);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);       
			encoder.encode(tag);                                               //近JPEG编码
			newimage.close();
			return activity;
			}catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
		int activityId = -1;
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		boolean isMultipart = ServletFileUpload.isMultipartContent(
				  request);
				  if (!isMultipart) {
				  System.out.println("File Not Uploaded");
				  } else {
				  FileItemFactory factory = new DiskFileItemFactory();
				  ServletFileUpload upload = new ServletFileUpload(factory);
				  List<?> items = null;
				  try {
				  items = upload.parseRequest(request);
				  System.out.println("items: "+items);
				  } catch (FileUploadException e) {
				  e.printStackTrace();
				  }
				  Iterator<?> itr = items.iterator();
				  
				  while (itr.hasNext()) {		    
				  FileItem item = (FileItem) itr.next();
					  if(item.getFieldName().equals("activity"))activityId = Integer.parseInt(item.getString());
						  if (!item.isFormField()){
							  if(item.getName()!=null&&item.getName()!="")
							  {
							  System.out.println("HERE");
							  String itemName = FilenameUtils.getName(item.getName());
							  
							  Random generator = new Random();
							  int r = Math.abs(generator.nextInt());

							  String reg = "[.*]";
							  String replacingtext = "";
							  
							  Pattern pattern = Pattern.compile(reg);
							  Matcher matcher = pattern.matcher(itemName);
							  StringBuffer buffer = new StringBuffer();

							  while (matcher.find()) {
							  matcher.appendReplacement(buffer, replacingtext);
							  }
							  int IndexOf = itemName.indexOf("."); 
							  String preFileName = itemName.substring(IndexOf);
							  String finalimage = buffer.toString()+"_"+r+preFileName;
							  String finalimageMin = buffer.toString()+"_min"+"_"+r+preFileName;
							  System.out.println("Final Image==="+finalimage);
							  String path = getServletContext().getRealPath("/");
							  System.out.println(path);
							  Properties pro = System.getProperties();
						         String osName = pro.getProperty("os.name");
						         File saveFile = null;
						         
						         String savePath = null;
						         String savePathMin = null;
						         
						         String relativeSavePath = null;
						         String relativeSavePathMin = null;
						         
						         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
						        	 savePath = path+"/postPictures/"+finalimage;
						        	 savePathMin = path+"/minPostPictures/"+finalimageMin;
						        	 saveFile = new File(savePath); 
						        	 
						         }
						         else{
						        	 savePath = path+"postPictures\\"+finalimage;
						        	 savePathMin = path+"minPostPictures\\"+finalimageMin;
						        	 saveFile = new File(savePath);
						         }
						         relativeSavePath = "postPictures/"+finalimage;
						         relativeSavePathMin = "minPostPictures/"+finalimageMin;
							  item.write(saveFile); 							 
							 PicTools.correctPicSize(savePath);
							 
							 ActivityDao activityDao = ActivityDao.getDao();
							 Activity activity = activityDao.getActivityById(activityId);
							 String preRealPath = path+activity.getPicWallAddress();
							 String preRealPathMin = path+activity.getPostAddress();
						     PicTools.DeletePic(preRealPath);
						     PicTools.DeletePic(preRealPathMin);
						     
						     
						     addConvertedPic(activity,saveFile,savePathMin,relativeSavePathMin);
						     activity.setPicWallAddress(relativeSavePath);
						     System.out.println(activity.getPicWallAddress());
						     System.out.println(activity.getPostAddress());
							 activityDao.updateActivity(activityId,activity);	 
						  }
						  }
						  LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
						  response.sendRedirect("./activities.jsp?league="+((Integer)luSessionCookieAccess.getLeagueId()).toString());
						  
					  
				  /*String name = item.getFieldName();
				  System.out.println("name: "+name);
				  String value = item.getString();
				  System.out.println("value: "+value);*/
				  }
				  }
				  }
		catch (Exception e) {
		e.printStackTrace();
	}

	}
	}	

